// Longevity History Analytics
// Analyzes browsing history for longevity-related insights

const longevityAnalytics = {
  data: null,
  paginationData: {
    domains: { currentPage: 1, itemsPerPage: 25, totalItems: 0, data: [] },
    urls: { currentPage: 1, itemsPerPage: 25, totalItems: 0, data: [] },
    busiest: { currentPage: 1, itemsPerPage: 50, totalItems: 0, data: [] }
  },
  currentSort: {
    domains: { column: 1, direction: 'desc' },
    urls: { column: 2, direction: 'desc' },
    busiest: { column: 1, direction: 'desc' }
  },

  // Site categories for longevity analysis
  siteCategories: {
    'productivity': ['google.com', 'docs.google.com', 'drive.google.com', 'notion.so', 'trello.com', 'asana.com', 'slack.com'],
    'entertainment': ['youtube.com', 'netflix.com', 'twitch.tv', 'spotify.com', 'facebook.com', 'instagram.com', 'tiktok.com', 'twitter.com', 'reddit.com'],
    'education': ['coursera.org', 'udemy.com', 'khanacademy.org', 'wikipedia.org', 'stackoverflow.com', 'github.com'],
    'news': ['news.google.com', 'cnn.com', 'bbc.com', 'nytimes.com', 'theguardian.com'],
    'shopping': ['amazon.com', 'ebay.com', 'etsy.com'],
    'health': ['webmd.com', 'mayoclinic.org', 'healthline.com', 'pubmed.ncbi.nlm.nih.gov'],
    'social': ['facebook.com', 'twitter.com', 'linkedin.com', 'instagram.com', 'pinterest.com'],
    'stress': ['news.google.com', 'reddit.com', 'twitter.com'] // Sites that may increase stress
  },

  // Analyze history for longevity insights
  async analyzeHistory() {
    console.log('Starting longevity history analysis...');
    
    const loadingEl = document.getElementById('loading');
    const mainContentEl = document.getElementById('main-content');
    
    if (loadingEl) {
      loadingEl.style.display = 'flex';
      loadingEl.innerHTML = '<div class="spinner"></div><p>Analyzing your browsing history for longevity insights...</p>';
    }
    if (mainContentEl) {
      mainContentEl.style.display = 'none';
    }
    
    try {
      const historyItems = await this.fetchHistory();
      if (!historyItems || historyItems.length === 0) {
        throw new Error('No history data available. Please browse some websites first.');
      }

      console.log(`Processing ${historyItems.length} history items...`);
      const processedData = this.processHistoryData(historyItems);
      this.data = processedData;
      
      // Calculate longevity-specific metrics
      const longevityMetrics = this.calculateLongevityMetrics(historyItems);
      
      // Store insights
      await this.saveInsights(longevityMetrics);
      
      // Display results
      this.displayResults(processedData, longevityMetrics);
      
      return { processedData, longevityMetrics };
    } catch (error) {
      console.error('Error analyzing history:', error);
      if (loadingEl) {
        loadingEl.style.display = 'flex';
        loadingEl.innerHTML = `
          <div style="text-align: center; padding: 40px; max-width: 600px;">
            <div style="font-size: 48px; margin-bottom: 20px;">⚠️</div>
            <h2 style="color: #f56565; margin-bottom: 15px;">Error Analyzing History</h2>
            <p style="color: #666; margin-bottom: 20px; line-height: 1.6;">${error.message}</p>
            <button onclick="location.reload()" class="btn-icon" style="background: #667eea; color: white; padding: 10px 20px; border: none; border-radius: 6px; cursor: pointer; margin: 10px;">
              Try Again
            </button>
            <p style="color: #999; margin-top: 20px; font-size: 12px; line-height: 1.6;">
              Make sure you have browsing history enabled in Chrome settings:<br>
              <strong>Settings → Privacy and security → Clear browsing data</strong>
            </p>
          </div>
        `;
      }
      if (mainContentEl) {
        mainContentEl.style.display = 'none';
      }
      throw error;
    }
  },

  // Fetch browsing history
  async fetchHistory() {
    try {
      // Check if chrome.history API is available
      if (!chrome || !chrome.history || !chrome.history.search) {
        console.error('History API not available:', {
          chrome: !!chrome,
          chromeHistory: !!(chrome && chrome.history),
          chromeHistorySearch: !!(chrome && chrome.history && chrome.history.search)
        });
        throw new Error('History API is not available. Please check that the extension has history permissions.');
      }

      // For Manifest V3, we use callback-based API
      const historyItems = await new Promise((resolve, reject) => {
        try {
          chrome.history.search({
            text: '',
            maxResults: 100000,
            startTime: 0
          }, (results) => {
            if (chrome.runtime.lastError) {
              console.error('Chrome runtime error:', chrome.runtime.lastError);
              reject(new Error(chrome.runtime.lastError.message || 'Failed to access browsing history'));
            } else {
              console.log(`Fetched ${results ? results.length : 0} history items`);
              resolve(results || []);
            }
          });
        } catch (error) {
          console.error('Error calling chrome.history.search:', error);
          reject(error);
        }
      });
        
      if (!historyItems || historyItems.length === 0) {
        throw new Error('No browsing history found. Please browse some websites first, then try again.');
      }
        
      return historyItems;
    } catch (error) {
      console.error('Error fetching history:', error);
      throw error;
    }
  },

  // Process history data
  processHistoryData(historyItems) {
    const data = {
      historyItems: historyItems.length,
      visitItems: 0,
      topDomains: [],
      topUrls: [],
      topBusiestDays: [],
      byDayHash: {},
      byHourHash: {},
      categoryStats: {}
    };

    const domainHash = {};
    const urlHash = {};
    const categoryHash = {};

    historyItems.forEach(item => {
      const domain = this.extractDomain(item.url);
      const visitCount = item.visitCount || 1;
      const date = new Date(item.lastVisitTime);
      
      data.visitItems += visitCount;

      // Domain statistics
      if (!domainHash[domain]) {
        domainHash[domain] = {
          visits: 0,
          category: this.categorizeDomain(domain)
        };
      }
      domainHash[domain].visits += visitCount;

      // URL statistics
      if (!urlHash[item.url]) {
        urlHash[item.url] = 0;
      }
      urlHash[item.url] += visitCount;

      // Category statistics
      const category = this.categorizeDomain(domain);
      if (!categoryHash[category]) {
        categoryHash[category] = 0;
      }
      categoryHash[category] += visitCount;

      // Group by day
      const dateKey = date.toISOString().split('T')[0];
      if (!data.byDayHash[dateKey]) {
        data.byDayHash[dateKey] = { count: 0, visits: 0 };
      }
      data.byDayHash[dateKey].count += visitCount;
      data.byDayHash[dateKey].visits += visitCount;

      // Group by hour
      const hour = date.getHours();
      if (!data.byHourHash[hour]) {
        data.byHourHash[hour] = 0;
      }
      data.byHourHash[hour] += visitCount;
    });

    // Convert to arrays and sort
    data.topDomains = this.convertDomainHashToArray(domainHash);
    data.topUrls = this.convertUrlHashToArray(urlHash);
    data.topBusiestDays = this.convertDayHashToArray(data.byDayHash);
    data.categoryStats = categoryHash;

    return data;
  },

  // Calculate longevity-specific metrics
  calculateLongevityMetrics(historyItems) {
    const metrics = {
      dailyScreenTime: 0,
      eveningUsage: 0,
      lateNightUsage: 0,
      productivityScore: 0,
      stressLevel: 0,
      sleepImpactScore: 0,
      totalDays: 0,
      hourlyPattern: new Array(24).fill(0),
      dayOfWeekPattern: new Array(7).fill(0)
    };

    if (historyItems.length === 0) return metrics;

    // Calculate date range
    const dates = historyItems.map(item => item.lastVisitTime);
    const minDate = new Date(Math.min(...dates));
    const maxDate = new Date(Math.max(...dates));
    const daysDiff = Math.ceil((maxDate - minDate) / (1000 * 60 * 60 * 24)) || 1;
    metrics.totalDays = daysDiff;

    // Calculate hourly patterns
    const hourlyVisits = new Array(24).fill(0);
    const dayOfWeekVisits = new Array(7).fill(0);
    let eveningVisits = 0;
    let lateNightVisits = 0;
    let productivityVisits = 0;
    let entertainmentVisits = 0;
    let stressVisits = 0;
    let totalVisits = 0;

    historyItems.forEach(item => {
      const date = new Date(item.lastVisitTime);
      const hour = date.getHours();
      const dayOfWeek = date.getDay();
      const visitCount = item.visitCount || 1;
      const domain = this.extractDomain(item.url);
      const category = this.categorizeDomain(domain);

      hourlyVisits[hour] += visitCount;
      dayOfWeekVisits[dayOfWeek] += visitCount;
      totalVisits += visitCount;

      // Evening usage (6PM-12AM)
      if (hour >= 18 && hour < 24) {
        eveningVisits += visitCount;
      }

      // Late night usage (10PM-2AM)
      if (hour >= 22 || hour < 2) {
        lateNightVisits += visitCount;
      }

      // Productivity vs entertainment
      if (this.isProductivitySite(domain)) {
        productivityVisits += visitCount;
      } else if (this.isEntertainmentSite(domain)) {
        entertainmentVisits += visitCount;
      }

      // Stress-inducing sites
      if (this.isStressSite(domain)) {
        stressVisits += visitCount;
      }
    });

    // Calculate metrics
    metrics.dailyScreenTime = (totalVisits / daysDiff / 60).toFixed(1); // Approximate hours (assuming 1 visit per minute)
    metrics.eveningUsage = totalVisits > 0 ? ((eveningVisits / totalVisits) * 100).toFixed(1) : 0;
    metrics.lateNightUsage = totalVisits > 0 ? ((lateNightVisits / totalVisits) * 100).toFixed(1) : 0;
    metrics.productivityScore = (productivityVisits + entertainmentVisits) > 0 
      ? Math.round((productivityVisits / (productivityVisits + entertainmentVisits)) * 100)
      : 50;
    metrics.stressLevel = totalVisits > 0 ? Math.round((stressVisits / totalVisits) * 100) : 0;
    metrics.sleepImpactScore = this.calculateSleepImpactScore(metrics.eveningUsage, metrics.lateNightUsage);
    metrics.hourlyPattern = hourlyVisits;
    metrics.dayOfWeekPattern = dayOfWeekVisits;

    return metrics;
  },

  // Calculate sleep impact score (0-100, higher = worse)
  calculateSleepImpactScore(eveningUsage, lateNightUsage) {
    const eveningScore = Math.min(eveningUsage / 2, 50); // Max 50 points
    const lateNightScore = Math.min(lateNightUsage * 2, 50); // Max 50 points
    return Math.round(eveningScore + lateNightScore);
  },

  // Categorize domain
  categorizeDomain(domain) {
    const lowerDomain = domain.toLowerCase();
    
    for (const [category, sites] of Object.entries(this.siteCategories)) {
      if (sites.some(site => lowerDomain.includes(site))) {
        return category;
      }
    }
    
    return 'other';
  },

  // Check if productivity site
  isProductivitySite(domain) {
    const lowerDomain = domain.toLowerCase();
    return this.siteCategories.productivity.some(site => lowerDomain.includes(site)) ||
           this.siteCategories.education.some(site => lowerDomain.includes(site));
  },

  // Check if entertainment site
  isEntertainmentSite(domain) {
    const lowerDomain = domain.toLowerCase();
    return this.siteCategories.entertainment.some(site => lowerDomain.includes(site));
  },

  // Check if stress-inducing site
  isStressSite(domain) {
    const lowerDomain = domain.toLowerCase();
    return this.siteCategories.stress.some(site => lowerDomain.includes(site));
  },

  // Extract domain from URL
  extractDomain(url) {
    try {
      const urlObj = new URL(url);
      return urlObj.hostname.replace('www.', '');
    } catch (e) {
      return url;
    }
  },

  // Convert domain hash to sorted array
  convertDomainHashToArray(hash) {
    const array = [];
    for (const key in hash) {
      array.push([key, hash[key].visits, hash[key].category]);
    }
    return array.sort((a, b) => b[1] - a[1]);
  },

  // Convert URL hash to sorted array
  convertUrlHashToArray(hash) {
    const array = [];
    for (const key in hash) {
      const domain = this.extractDomain(key);
      array.push([key, hash[key], domain]);
    }
    return array.sort((a, b) => b[1] - a[1]);
  },

  // Convert day hash to sorted array
  convertDayHashToArray(hash) {
    const array = [];
    for (const key in hash) {
      const date = new Date(key);
      const formattedDate = date.toLocaleDateString('en-US', { 
        weekday: 'short', 
        month: 'short', 
        day: 'numeric',
        year: 'numeric'
      });
      const screenTime = (hash[key].visits / 60).toFixed(1); // Approximate hours
      array.push([key, hash[key].visits, formattedDate, screenTime]);
    }
    return array.sort((a, b) => b[1] - a[1]);
  },

  // Save insights to storage
  async saveInsights(metrics) {
    try {
      const insights = {
        lastUpdated: Date.now(),
        metrics: metrics,
        recommendations: this.generateRecommendations(metrics)
      };
      await chrome.storage.local.set({ longevityHistoryInsights: insights });
    } catch (error) {
      console.error('Error saving insights:', error);
    }
  },

  // Generate recommendations based on metrics
  generateRecommendations(metrics) {
    const recommendations = [];

    if (metrics.sleepImpactScore > 60) {
      recommendations.push({
        type: 'sleep',
        priority: 'high',
        text: 'High evening/late-night usage detected. Consider reducing screen time 2 hours before bed to improve sleep quality.'
      });
    } else if (metrics.sleepImpactScore > 40) {
      recommendations.push({
        type: 'sleep',
        priority: 'medium',
        text: 'Moderate evening usage. Try to avoid screens 1 hour before bedtime for better sleep.'
      });
    }

    if (metrics.productivityScore < 30) {
      recommendations.push({
        type: 'productivity',
        priority: 'medium',
        text: 'Low productivity score. Consider balancing entertainment with educational or productivity sites.'
      });
    }

    if (metrics.stressLevel > 40) {
      recommendations.push({
        type: 'stress',
        priority: 'high',
        text: 'High stress-inducing site usage. Consider taking breaks from news and social media for better mental health.'
      });
    }

    if (parseFloat(metrics.dailyScreenTime) > 8) {
      recommendations.push({
        type: 'screen-time',
        priority: 'high',
        text: 'High daily screen time detected. Consider taking regular breaks and implementing screen-free periods.'
      });
    }

    if (recommendations.length === 0) {
      recommendations.push({
        type: 'general',
        priority: 'low',
        text: 'Great job! Your browsing habits appear well-balanced. Keep maintaining healthy digital habits.'
      });
    }

    return recommendations;
  },

  // Display results
  displayResults(data, metrics) {
    console.log('Displaying results...', { data, metrics });
    
    const loadingEl = document.getElementById('loading');
    const mainContentEl = document.getElementById('main-content');
    
    if (loadingEl) {
      loadingEl.style.display = 'none';
    }
    
    if (mainContentEl) {
      mainContentEl.style.display = 'block';
    } else {
      console.error('Main content element not found!');
      return;
    }

    try {
      // Update insight cards
      this.updateInsightCards(data, metrics);
      
      // Update charts (with Chart.js) - wait for Chart.js to be available
      const renderCharts = () => {
        if (typeof Chart !== 'undefined') {
          this.renderHourlyChart(metrics.hourlyPattern);
          this.renderDayOfWeekChart(metrics.dayOfWeekPattern);
          this.renderCategoryPieChart(data.categoryStats);
          this.renderTrendChart(data);
        } else {
          console.warn('Chart.js not available, using legacy charts');
          // Fallback to legacy charts if Chart.js not loaded
          this.renderHourlyChartLegacy(metrics.hourlyPattern);
          this.renderDayOfWeekChartLegacy(metrics.dayOfWeekPattern);
        }
      };
      
      // Try immediately, then retry after a short delay if Chart.js not ready
      renderCharts();
      setTimeout(renderCharts, 200);
      setTimeout(renderCharts, 1000); // One more retry in case Chart.js loads slowly
      
      // Update sleep analysis
      this.updateSleepAnalysis(metrics);
      
      // Update category breakdown
      this.updateCategoryBreakdown(data.categoryStats);
      
      // Populate tables
      this.populateTables(data);
      
      // Update chart insights
      this.updateChartInsights(metrics);
      
      // Update summary
      this.updateSummary(data, metrics);
      
      console.log('Results displayed successfully');
    } catch (error) {
      console.error('Error displaying results:', error);
      if (loadingEl) {
        loadingEl.style.display = 'flex';
        loadingEl.innerHTML = `
          <div style="text-align: center; padding: 40px;">
            <div style="font-size: 48px; margin-bottom: 20px;">❌</div>
            <h2 style="color: #f56565; margin-bottom: 15px;">Error Displaying Results</h2>
            <p style="color: #666; margin-bottom: 20px;">${error.message}</p>
            <button onclick="location.reload()" class="btn-icon" style="background: #667eea; color: white; padding: 10px 20px; border: none; border-radius: 6px; cursor: pointer;">
              Reload Page
            </button>
          </div>
        `;
      }
      if (mainContentEl) {
        mainContentEl.style.display = 'none';
      }
    }
  },

  // Update insight cards
  updateInsightCards(data, metrics) {
    document.getElementById('daily-screen-time').textContent = metrics.dailyScreenTime + 'h';
    document.getElementById('sleep-impact').textContent = metrics.sleepImpactScore + '/100';
    document.getElementById('productivity-score').textContent = metrics.productivityScore + '%';
    document.getElementById('stress-level').textContent = metrics.stressLevel + '%';
    document.getElementById('top-domain').textContent = data.topDomains.length > 0 ? data.topDomains[0][0] : '-';
    document.getElementById('top-domain-visits').textContent = data.topDomains.length > 0 
      ? data.topDomains[0][1] + ' visits' : '-';
    document.getElementById('active-days').textContent = metrics.totalDays;

    // Update card colors based on scores
    const sleepCard = document.getElementById('sleep-impact-card');
    if (metrics.sleepImpactScore > 60) {
      sleepCard.classList.add('warning');
    } else if (metrics.sleepImpactScore < 40) {
      sleepCard.classList.add('positive');
    }

    const productivityCard = document.getElementById('productivity-card');
    if (metrics.productivityScore > 60) {
      productivityCard.classList.add('positive');
    } else if (metrics.productivityScore < 40) {
      productivityCard.classList.add('warning');
    }

    const stressCard = document.getElementById('stress-card');
    if (metrics.stressLevel > 40) {
      stressCard.classList.add('warning');
    } else if (metrics.stressLevel < 20) {
      stressCard.classList.add('positive');
    }
  },

  // Update sleep analysis
  updateSleepAnalysis(metrics) {
    document.getElementById('evening-usage').textContent = metrics.eveningUsage + '%';
    document.getElementById('late-night-usage').textContent = metrics.lateNightUsage + '%';
    
    // Update progress bars
    document.getElementById('evening-bar').style.width = metrics.eveningUsage + '%';
    document.getElementById('late-night-bar').style.width = metrics.lateNightUsage + '%';

    // Update recommendations
    const recommendations = this.generateRecommendations(metrics);
    const list = document.getElementById('sleep-recommendations-list');
    list.innerHTML = '';
    recommendations.forEach(rec => {
      const li = document.createElement('li');
      li.textContent = rec.text;
      if (rec.priority === 'high') {
        li.classList.add('priority-high');
      }
      list.appendChild(li);
    });
  },

  // Update category breakdown
  updateCategoryBreakdown(categoryStats) {
    const container = document.getElementById('category-breakdown');
    const total = Object.values(categoryStats).reduce((sum, val) => sum + val, 0);
    
    if (total === 0) {
      container.innerHTML = '<p>No category data available</p>';
      return;
    }

    const sortedCategories = Object.entries(categoryStats)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 10);

    container.innerHTML = sortedCategories.map(([category, count]) => {
      const percentage = ((count / total) * 100).toFixed(1);
      return `
        <div class="category-item">
          <div class="category-name">${category.charAt(0).toUpperCase() + category.slice(1)}</div>
          <div class="category-bar">
            <div class="category-bar-fill" style="width: ${percentage}%"></div>
          </div>
          <div class="category-value">${percentage}%</div>
        </div>
      `;
    }).join('');
  },

  // Update chart insights
  updateChartInsights(metrics) {
    // Find peak hours
    const peakHour = metrics.hourlyPattern.indexOf(Math.max(...metrics.hourlyPattern));
    const peakHourFormatted = this.formatHour(peakHour);
    
    document.getElementById('hourly-insight').textContent = 
      `Peak browsing activity occurs at ${peakHourFormatted}. ${
        peakHour >= 22 || peakHour < 6 
          ? 'Consider reducing late-night usage for better sleep.' 
          : 'Your activity pattern looks healthy.'}`;

    // Find peak day
    const peakDay = metrics.dayOfWeekPattern.indexOf(Math.max(...metrics.dayOfWeekPattern));
    const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    
    document.getElementById('day-insight').textContent = 
      `Most active day: ${dayNames[peakDay]}. Average activity is distributed across the week.`;
  },

  // Render hourly chart using Chart.js
  renderHourlyChart(hourlyData) {
    const canvas = document.getElementById('hourly-chart-canvas');
    if (!canvas) {
      // Fallback to old method if canvas not found
      this.renderHourlyChartLegacy(hourlyData);
      return;
    }

    const ctx = canvas.getContext('2d');
    
    // Destroy existing chart if it exists
    if (this.hourlyChart) {
      this.hourlyChart.destroy();
    }

    const labels = Array.from({ length: 24 }, (_, i) => this.formatHour(i));
    
    // Color bars based on time of day (evening/late night = red, morning = green)
    const colors = hourlyData.map((_, hour) => {
      if (hour >= 22 || hour < 6) return 'rgba(245, 101, 101, 0.8)'; // Late night - red
      if (hour >= 18 && hour < 22) return 'rgba(255, 193, 7, 0.8)'; // Evening - orange
      if (hour >= 6 && hour < 12) return 'rgba(72, 187, 120, 0.8)'; // Morning - green
      return 'rgba(102, 126, 234, 0.8)'; // Day - blue
    });

    this.hourlyChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{
          label: 'Visits',
          data: hourlyData,
          backgroundColor: colors,
          borderColor: colors.map(c => c.replace('0.8', '1')),
          borderWidth: 1
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                return context.parsed.y + ' visits';
              }
            }
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            ticks: {
              precision: 0
            },
            title: {
              display: true,
              text: 'Number of Visits'
            }
          },
          x: {
            title: {
              display: true,
              text: 'Hour of Day'
            }
          }
        }
      }
    });
  },

  // Legacy chart rendering (fallback)
  renderHourlyChartLegacy(hourlyData) {
    const maxVisits = Math.max(...hourlyData);
    if (maxVisits === 0) return;

    const chartBars = document.getElementById('hourly-chart-bars');
    const chartLabels = document.getElementById('hourly-chart-labels');
    const chartAxisY = document.getElementById('hourly-chart-axis-y');

    if (!chartBars) return;

    chartBars.innerHTML = '';
    chartLabels.innerHTML = '';
    if (chartAxisY) chartAxisY.innerHTML = '';

    // Y-axis labels
    if (chartAxisY) {
      for (let i = 0; i <= 4; i++) {
        const value = Math.round((maxVisits / 4) * i);
        const yLabel = document.createElement('div');
        yLabel.className = 'chart-axis-y-label';
        yLabel.textContent = value.toLocaleString();
        chartAxisY.appendChild(yLabel);
      }
    }

    // Bars and labels
    for (let hour = 0; hour < 24; hour++) {
      const visits = hourlyData[hour];
      const height = maxVisits > 0 ? (visits / maxVisits) * 150 : 0;

      const bar = document.createElement('div');
      bar.className = 'chart-bar';
      bar.style.height = height + 'px';
      
      const tooltip = document.createElement('div');
      tooltip.className = 'chart-bar-tooltip';
      tooltip.style.bottom = height > 75 ? '50%' : '100%';
      tooltip.style.transform = height > 75 
        ? 'translateX(-50%) translateY(50%)' 
        : 'translateX(-50%)';
      tooltip.innerHTML = `<strong>${this.formatHour(hour)}</strong><br>${visits} visits`;
      bar.appendChild(tooltip);
      
      chartBars.appendChild(bar);

      const label = document.createElement('div');
      label.className = 'chart-label';
      label.textContent = this.formatHour(hour);
      chartLabels.appendChild(label);
    }
  },

  // Render day of week chart using Chart.js
  renderDayOfWeekChart(dayData) {
    const canvas = document.getElementById('day-chart-canvas');
    if (!canvas) {
      // Fallback to old method if canvas not found
      this.renderDayOfWeekChartLegacy(dayData);
      return;
    }

    const ctx = canvas.getContext('2d');
    
    // Destroy existing chart if it exists
    if (this.dayChart) {
      this.dayChart.destroy();
    }

    const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    
    this.dayChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: dayNames,
        datasets: [{
          label: 'Visits',
          data: dayData,
          backgroundColor: 'rgba(102, 126, 234, 0.8)',
          borderColor: 'rgba(102, 126, 234, 1)',
          borderWidth: 1
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                return context.parsed.y + ' visits';
              }
            }
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            ticks: {
              precision: 0
            },
            title: {
              display: true,
              text: 'Number of Visits'
            }
          },
          x: {
            title: {
              display: true,
              text: 'Day of Week'
            }
          }
        }
      }
    });
  },

  // Legacy chart rendering (fallback)
  renderDayOfWeekChartLegacy(dayData) {
    const maxVisits = Math.max(...dayData);
    if (maxVisits === 0) return;

    const chartBars = document.getElementById('day-chart-bars');
    const chartLabels = document.getElementById('day-chart-labels');
    const chartAxisY = document.getElementById('day-chart-axis-y');

    if (!chartBars) return;

    chartBars.innerHTML = '';
    chartLabels.innerHTML = '';
    if (chartAxisY) chartAxisY.innerHTML = '';

    // Y-axis labels
    if (chartAxisY) {
      for (let i = 0; i <= 4; i++) {
        const value = Math.round((maxVisits / 4) * i);
        const yLabel = document.createElement('div');
        yLabel.className = 'chart-axis-y-label';
        yLabel.textContent = value.toLocaleString();
        chartAxisY.appendChild(yLabel);
      }
    }

    const dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    
    for (let day = 0; day < 7; day++) {
      const visits = dayData[day];
      const height = maxVisits > 0 ? (visits / maxVisits) * 150 : 0;

      const bar = document.createElement('div');
      bar.className = 'chart-bar';
      bar.style.height = height + 'px';
      
      const tooltip = document.createElement('div');
      tooltip.className = 'chart-bar-tooltip';
      tooltip.style.bottom = height > 75 ? '50%' : '100%';
      tooltip.style.transform = height > 75 
        ? 'translateX(-50%) translateY(50%)' 
        : 'translateX(-50%)';
      tooltip.innerHTML = `<strong>${dayNames[day]}</strong><br>${visits} visits`;
      bar.appendChild(tooltip);
      
      chartBars.appendChild(bar);

      const label = document.createElement('div');
      label.className = 'chart-label';
      label.textContent = dayNames[day];
      chartLabels.appendChild(label);
    }
  },

  // Render category pie chart using Chart.js
  renderCategoryPieChart(categoryStats) {
    const canvas = document.getElementById('category-pie-chart-canvas');
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    
    // Destroy existing chart if it exists
    if (this.categoryChart) {
      this.categoryChart.destroy();
    }

    const sortedCategories = Object.entries(categoryStats)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 10);

    const labels = sortedCategories.map(([cat]) => cat.charAt(0).toUpperCase() + cat.slice(1));
    const data = sortedCategories.map(([, count]) => count);
    
    const colors = [
      'rgba(102, 126, 234, 0.8)',
      'rgba(72, 187, 120, 0.8)',
      'rgba(245, 101, 101, 0.8)',
      'rgba(255, 193, 7, 0.8)',
      'rgba(139, 92, 246, 0.8)',
      'rgba(236, 72, 153, 0.8)',
      'rgba(59, 130, 246, 0.8)',
      'rgba(34, 197, 94, 0.8)',
      'rgba(249, 115, 22, 0.8)',
      'rgba(168, 85, 247, 0.8)'
    ];

    this.categoryChart = new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: labels,
        datasets: [{
          data: data,
          backgroundColor: colors.slice(0, labels.length),
          borderWidth: 2,
          borderColor: '#fff'
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'right',
            labels: {
              padding: 15,
              usePointStyle: true
            }
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                const label = context.label || '';
                const value = context.parsed || 0;
                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                const percentage = ((value / total) * 100).toFixed(1);
                return `${label}: ${value.toLocaleString()} visits (${percentage}%)`;
              }
            }
          }
        }
      }
    });
  },

  // Render trend chart (activity over time)
  renderTrendChart(data) {
    const canvas = document.getElementById('trend-chart-canvas');
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    
    // Destroy existing chart if it exists
    if (this.trendChart) {
      this.trendChart.destroy();
    }

    // Sort days chronologically
    const sortedDays = Object.entries(data.byDayHash)
      .sort((a, b) => new Date(a[0]) - new Date(b[0]))
      .slice(-30); // Last 30 days

    const labels = sortedDays.map(([date]) => {
      const d = new Date(date);
      return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
    });
    const visits = sortedDays.map(([, data]) => data.visits);

    this.trendChart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: 'Daily Visits',
          data: visits,
          borderColor: 'rgba(102, 126, 234, 1)',
          backgroundColor: 'rgba(102, 126, 234, 0.1)',
          borderWidth: 2,
          fill: true,
          tension: 0.4,
          pointRadius: 3,
          pointHoverRadius: 5
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                return context.parsed.y + ' visits';
              }
            }
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            ticks: {
              precision: 0
            },
            title: {
              display: true,
              text: 'Number of Visits'
            }
          },
          x: {
            title: {
              display: true,
              text: 'Date'
            }
          }
        }
      }
    });
  },

  // Update summary section
  updateSummary(data, metrics) {
    const summaryEl = document.getElementById('longevity-summary');
    if (!summaryEl) return;

    const totalVisits = data.visitItems || 0;
    const avgDailyVisits = metrics.totalDays > 0 ? Math.round(totalVisits / metrics.totalDays) : 0;
    
    // Calculate health score (0-100)
    let healthScore = 100;
    healthScore -= Math.min(metrics.sleepImpactScore * 0.5, 30); // Sleep impact
    healthScore -= Math.max(0, (metrics.stressLevel - 20) * 0.5); // Stress level
    healthScore += Math.max(0, (metrics.productivityScore - 50) * 0.2); // Productivity bonus
    healthScore = Math.max(0, Math.min(100, Math.round(healthScore)));

    // Generate personalized insights
    const insights = [];
    
    if (metrics.sleepImpactScore > 60) {
      insights.push({
        icon: '🌙',
        type: 'warning',
        text: 'High evening/late-night usage detected. Reducing screen time 2 hours before bed can significantly improve sleep quality and longevity.'
      });
    }
    
    if (metrics.productivityScore > 60) {
      insights.push({
        icon: '📚',
        type: 'positive',
        text: 'Great! You spend a good portion of your time on productive and educational sites.'
      });
    } else if (metrics.productivityScore < 30) {
      insights.push({
        icon: '📚',
        type: 'warning',
        text: 'Consider balancing entertainment with educational content for better cognitive health.'
      });
    }
    
    if (metrics.stressLevel > 40) {
      insights.push({
        icon: '🧘',
        type: 'warning',
        text: 'High exposure to stress-inducing sites. Consider taking breaks from news and social media for better mental health.'
      });
    }
    
    if (parseFloat(metrics.dailyScreenTime) > 8) {
      insights.push({
        icon: '⏰',
        type: 'warning',
        text: 'High daily screen time detected. Consider implementing screen-free periods and regular breaks.'
      });
    } else if (parseFloat(metrics.dailyScreenTime) < 3) {
      insights.push({
        icon: '✅',
        type: 'positive',
        text: 'Your screen time is well-balanced. Keep maintaining healthy digital habits!'
      });
    }

    if (insights.length === 0) {
      insights.push({
        icon: '🌟',
        type: 'positive',
        text: 'Your browsing habits appear well-balanced. Keep maintaining healthy digital habits for longevity!'
      });
    }

    summaryEl.innerHTML = `
      <div class="summary-content">
        <div class="summary-header">
          <h3>📊 Activity Summary</h3>
          <div class="health-score">
            <div class="health-score-label">Longevity Health Score</div>
            <div class="health-score-value ${healthScore >= 70 ? 'positive' : healthScore >= 50 ? 'warning' : 'negative'}">
              ${healthScore}/100
            </div>
          </div>
        </div>
        <div class="summary-stats">
          <div class="summary-stat">
            <span class="stat-icon">📈</span>
            <div>
              <div class="stat-value">${totalVisits.toLocaleString()}</div>
              <div class="stat-label">Total Visits</div>
            </div>
          </div>
          <div class="summary-stat">
            <span class="stat-icon">📅</span>
            <div>
              <div class="stat-value">${metrics.totalDays}</div>
              <div class="stat-label">Active Days</div>
            </div>
          </div>
          <div class="summary-stat">
            <span class="stat-icon">📊</span>
            <div>
              <div class="stat-value">${avgDailyVisits}</div>
              <div class="stat-label">Avg Daily Visits</div>
            </div>
          </div>
          <div class="summary-stat">
            <span class="stat-icon">🌐</span>
            <div>
              <div class="stat-value">${data.topDomains.length}</div>
              <div class="stat-label">Unique Domains</div>
            </div>
          </div>
        </div>
        <div class="summary-insights">
          <h4>💡 Key Insights</h4>
          ${insights.map(insight => `
            <div class="insight-item ${insight.type}">
              <span class="insight-icon">${insight.icon}</span>
              <span class="insight-text">${insight.text}</span>
            </div>
          `).join('')}
        </div>
      </div>
    `;
  },

  // Format hour
  formatHour(hour) {
    if (hour === 0) return '12am';
    if (hour < 12) return hour + 'am';
    if (hour === 12) return '12pm';
    return (hour - 12) + 'pm';
  },

  // Populate tables
  populateTables(data) {
    this.paginationData.domains.data = data.topDomains;
    this.paginationData.domains.totalItems = data.topDomains.length;
    
    this.paginationData.urls.data = data.topUrls;
    this.paginationData.urls.totalItems = data.topUrls.length;
    
    this.paginationData.busiest.data = data.topBusiestDays;
    this.paginationData.busiest.totalItems = data.topBusiestDays.length;

    this.renderTable('domains');
    this.renderTable('urls');
    this.renderTable('busiest');
  },

  // Render table
  renderTable(tableType) {
    const data = this.paginationData[tableType];
    const startIndex = (data.currentPage - 1) * data.itemsPerPage;
    const endIndex = startIndex + data.itemsPerPage;
    const pageData = data.data.slice(startIndex, endIndex);
    
    const tbody = document.getElementById(tableType + '-tbody');
    tbody.innerHTML = '';
    
    const totalVisits = this.data ? this.data.visitItems : 0;

    if (tableType === 'domains') {
      pageData.forEach(item => {
        const row = document.createElement('tr');
        const percentage = totalVisits > 0 ? ((item[1] / totalVisits) * 100).toFixed(1) + '%' : '0%';
        row.innerHTML = `
          <td class="domain-cell">${item[0]}</td>
          <td class="visit-count">${item[1].toLocaleString()}</td>
          <td class="category-cell">${item[2]}</td>
          <td class="percentage">${percentage}</td>
        `;
        tbody.appendChild(row);
      });
    } else if (tableType === 'urls') {
      pageData.forEach(item => {
        const row = document.createElement('tr');
        const displayUrl = item[0].length > 50 ? item[0].substring(0, 50) + '...' : item[0];
        row.innerHTML = `
          <td class="url-cell"><a href="${item[0]}" target="_blank" title="${item[0]}">${displayUrl}</a></td>
          <td class="domain-cell">${item[2]}</td>
          <td class="visit-count">${item[1].toLocaleString()}</td>
        `;
        tbody.appendChild(row);
      });
    } else if (tableType === 'busiest') {
      pageData.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
          <td class="date-cell">${item[2]}</td>
          <td class="visit-count">${item[1].toLocaleString()}</td>
          <td class="screen-time-cell">${item[3]}h</td>
        `;
        tbody.appendChild(row);
      });
    }
    
    this.updatePaginationInfo(tableType);
  },

  // Update pagination info
  updatePaginationInfo(tableType) {
    const data = this.paginationData[tableType];
    const totalPages = Math.ceil(data.totalItems / data.itemsPerPage);
    const pageInfo = document.getElementById(tableType + '-page-info');
    pageInfo.textContent = `Page ${data.currentPage} of ${totalPages}`;
    
    const paginationDiv = document.getElementById(tableType + '-pagination');
    const buttons = paginationDiv.querySelectorAll('button');
    if (buttons.length >= 2) {
      buttons[0].disabled = data.currentPage <= 1;
      buttons[1].disabled = data.currentPage >= totalPages;
    }
  }
};

// Global functions for pagination and sorting
function changePage(tableType, direction) {
  const data = longevityAnalytics.paginationData[tableType];
  const totalPages = Math.ceil(data.totalItems / data.itemsPerPage);
  
  if (direction === 'prev' && data.currentPage > 1) {
    data.currentPage--;
  } else if (direction === 'next' && data.currentPage < totalPages) {
    data.currentPage++;
  }
  
  longevityAnalytics.renderTable(tableType);
}

function sortTable(tableType, columnIndex) {
  const data = longevityAnalytics.paginationData[tableType];
  const sort = longevityAnalytics.currentSort[tableType];
  
  const direction = sort.column === columnIndex && sort.direction === 'asc' ? 'desc' : 'asc';
  longevityAnalytics.currentSort[tableType] = { column: columnIndex, direction };
  
  data.data.sort((a, b) => {
    const aValue = a[columnIndex];
    const bValue = b[columnIndex];
    
    if (typeof aValue === 'number' && typeof bValue === 'number') {
      return direction === 'asc' ? aValue - bValue : bValue - aValue;
    }
    
    const aStr = String(aValue).toLowerCase();
    const bStr = String(bValue).toLowerCase();
    return direction === 'asc' ? aStr.localeCompare(bStr) : bStr.localeCompare(aStr);
  });
  
  data.currentPage = 1;
  longevityAnalytics.renderTable(tableType);
}

function exportToCSV(tableType) {
  const data = longevityAnalytics.paginationData[tableType].data;
  if (!data || data.length === 0) {
    alert('No data available to export');
    return;
  }
  
  let csv = [];
  const table = document.getElementById(tableType + '-table');
  const headers = Array.from(table.querySelectorAll('thead th')).map(th => 
    '"' + th.textContent.replace(' ↕', '').replace(/"/g, '""') + '"'
  );
  csv.push(headers.join(','));
  
  const totalVisits = longevityAnalytics.data ? longevityAnalytics.data.visitItems : 0;
  
  data.forEach(item => {
    const row = [];
    if (tableType === 'domains') {
      const percentage = totalVisits > 0 ? ((item[1] / totalVisits) * 100).toFixed(1) + '%' : '0%';
      row.push('"' + String(item[0]).replace(/"/g, '""') + '"');
      row.push(item[1]);
      row.push('"' + String(item[2]).replace(/"/g, '""') + '"');
      row.push('"' + percentage + '"');
    } else if (tableType === 'urls') {
      row.push('"' + String(item[0]).replace(/"/g, '""') + '"');
      row.push('"' + String(item[2]).replace(/"/g, '""') + '"');
      row.push(item[1]);
    } else if (tableType === 'busiest') {
      row.push('"' + String(item[2]).replace(/"/g, '""') + '"');
      row.push(item[1]);
      row.push('"' + String(item[3]).replace(/"/g, '""') + '"');
    }
    csv.push(row.join(','));
  });
  
  const csvContent = csv.join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `longevity-history-${tableType}-${new Date().toISOString().split('T')[0]}.csv`;
  link.click();
  URL.revokeObjectURL(url);
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', async () => {
  console.log('History Analytics page loaded');
  
  // Setup navigation
  const backBtn = document.getElementById('backBtn');
  const refreshBtn = document.getElementById('refreshBtn');
  
  if (backBtn) {
    backBtn.addEventListener('click', () => {
      window.location.href = 'newtab.html';
    });
  }
  
  if (refreshBtn) {
    refreshBtn.addEventListener('click', () => {
      location.reload();
    });
  }
  
  // Check if required elements exist
  const loadingEl = document.getElementById('loading');
  const mainContentEl = document.getElementById('main-content');
  
  if (!loadingEl) {
    console.error('Loading element not found!');
    return;
  }
  
  if (!mainContentEl) {
    console.error('Main content element not found!');
    return;
  }
  
  // Start analysis
  try {
    console.log('Starting history analysis...');
    await longevityAnalytics.analyzeHistory();
  } catch (error) {
    console.error('Failed to analyze history:', error);
    // Error should already be displayed in analyzeHistory, but ensure loading is visible
    if (loadingEl && loadingEl.style.display === 'none') {
      loadingEl.style.display = 'flex';
    }
  }
});

// Make functions globally accessible
window.longevityAnalytics = longevityAnalytics;
window.changePage = changePage;
window.sortTable = sortTable;
window.exportToCSV = exportToCSV;
